home *** CD-ROM | disk | FTP | other *** search
- Path: news.cis.ohio-state.edu!usenet
- From: jun xu <jun@cis.ohio-state.edu>
- Newsgroups: comp.lang.c
- Subject: Why I can not bind
- Date: Wed, 21 Feb 1996 15:55:11 -0500
- Organization: The Ohio State University Dept. of Computer and Info. Science
- Message-ID: <312B86AF.165F@cis.ohio-state.edu>
- NNTP-Posting-Host: crumble.cis.ohio-state.edu
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (X11; I; HP-UX A.09.05 9000/715)
-
- I am learning to write a simple server using C and
- socket routines. I encounter the run time error of
- "Unable to bind". Here below is the code. Thanks in
- advance for the help. (Actually it is Richard
- Steven's code and not mine)
-
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
-
- #define SERV_HOST_ADDR "164.107.128.3"
- #define SERV_TCP_PORT 8888
- char goodword[] = "Hello World";
-
- int writen(fd, ptr, nbytes)
- int fd;
- char *ptr;
- int nbytes;
- {
- int nleft, nwritten;
- nleft = nbytes;
- while (nleft > 0) {
- nwritten = write(fd, ptr, nleft);
- if (nwritten <= 0)
- return nwritten;
- nleft -= nwritten;
- ptr += nwritten;
- }
- return nbytes - nleft;
- }
-
- main(argc, argv)
- int argc;
- char *argv[];
- {
- int sockfd, newsockfd, clilen, childpid;
- struct sockaddr_in cli_addr, serv_addr;
- if (sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0) {
- printf("Unable to open socket!");
- exit(1);
- }
- bzero((char*)&serv_addr, sizeof(serv_addr));
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR);
- serv_addr.sin_port = htons(SERV_TCP_PORT);
- if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) <
- 0) {
- printf("Unable to bind");
- exit(1);
- }
- listen(sockfd, 5);
- for (;;) {
- clilen = sizeof(cli_addr);
- newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen);
- if (newsockfd < 0) {
- printf("Unable to accept");
- exit(1);
- }
- if ((childpid = fork()) < 0) {
- printf("Unable to fork!");
- exit(1);
- }
- else if (childpid == 0) {
- close(sockfd);
- if(writen(newsockfd, goodword, 11) != 11) {
- printf("Socket write error");
- exit(1);
- }
- exit(0);
- }
- }
- }
-